from django.http import JsonResponse
import copy
# from django.contrib.auth.models import User
# from django.contrib.auth import authenticate, login as _login, logout
from django.views.decorators.csrf import csrf_exempt
from .login_utils import get_login_user, set_logout, is_login, set_login, get_ip


from .models import BlogItem


# json返回结果的默认结构
JSONResult = dict(result=0, datas=[], message="")


@csrf_exempt
def add_blog(request):
    """
    发布博客
    :param request:
    :return:
    """
    result = copy.deepcopy(JSONResult)
    token = request.POST.get('token', '')
    if not token:
        result['message'] = "未传递有效的token，不可访问"
    elif is_login(request, token):
        content = request.POST.get("content", '').strip()
        nickname = request.POST.get('nickname', '').strip()
        portrait = request.POST.get('portrait', '').strip()

        if not content or not nickname or not portrait:
            result['result'] = -2
            result['message'] = '昵称，头像，和发布内容不能为空'
        elif BlogItem.objects.filter(nickname=nickname).exclude(user=request.user).count() > 0:
            result['result'] = -3
            result['message'] = '此昵称已被别人使用过'
        else:
            ip = get_ip(request)
            blog = BlogItem(user=request.user, content=content, nickname=nickname, portrait=portrait, ip=ip)
            blog.save()
            result['result'] = 1
            result['message'] = "发布成功"
    else:
        result['result'] = -1
        result['message'] = "未登录，不可访问"
    return JsonResponse(result)


@csrf_exempt
def query_blog(request):
    """
    查询博客列表
    :param request:
    :return:
    """
    result = copy.deepcopy(JSONResult)
    datas = [dict(id=blog.id,
                  username=blog.user.username,
                  portrait=blog.portrait,
                  content=blog.content,
                  nickname=blog.nickname,
                  ip=blog.ip)
             for blog in BlogItem.objects.filter(is_del=0).order_by("-id")[:1000]]
    result['result'] = 1
    result['datas'] = datas
    return JsonResponse(result)


@csrf_exempt
def query_user_blog(request):
    """
    查询指定用户的博客列表
    :param request:
    :return:
    """
    username = request.GET.get('username', '').strip()
    result = copy.deepcopy(JSONResult)
    datas = [dict(id=blog.id,
                  username=blog.user.username,
                  portrait=blog.portrait,
                  content=blog.content,
                  nickname=blog.nickname,
                  ip=blog.ip)
             for blog in BlogItem.objects.filter(is_del=0, user__username=username).order_by("-id")[:1000]]
    result['result'] = 1
    result['datas'] = datas
    return JsonResponse(result)


@csrf_exempt
def query_self_blog(request):
    """
    查询自己发布的博客列表
    :param request:
    :return:
    """
    result = copy.deepcopy(JSONResult)
    token = request.GET.get('token', '')
    if not token:
        result['message'] = "未传递有效的token，不可访问"
    elif is_login(request, token):
        data_list = [dict(id=blog.id, username=blog.user.username, portrait=blog.portrait,
                          content=blog.content, nickname=blog.nickname, ip=blog.ip)
                     for blog in BlogItem.objects.filter(is_del=0, user=request.user).order_by("-id")]
        result['result'] = 1
        result['datas'] = data_list
    else:
        result['result'] = -1
        result['message'] = "未登录，不可访问"
    return JsonResponse(result)


@csrf_exempt
def del_blog(request):
    """
    删除自己的微博
    :param request:
    :return:
    """
    result = copy.deepcopy(JSONResult)
    token = request.POST.get('token', '')
    if not token:
        result['message'] = "未传递有效的token，不可访问"
    elif is_login(request, token):
        blog_id = request.POST.get('id', '')
        if not blog_id or not blog_id.isnumeric():
            result['result'] = -2
            result['message'] = "id不能为空且必须为数字"
        else:
            blog = BlogItem.objects.filter(id=blog_id)
            print(blog[0].user == request.user)
            if not blog:
                result['result'] = -3
                result['message'] = "指定的微博不存在"
            elif blog[0].user != request.user:
                result['result'] = -4
                result['message'] = "不能删除别人发布的微博"
            else:
                blog.update(is_del=1)
                result['result'] = 1
                result['message'] = "删除成功"
    else:
        result['result'] = -1
        result['message'] = "未登录，不可访问"

    return JsonResponse(result)
